package com.app;

import java.util.ArrayList;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import com.app.task.Task;
import java.util.concurrent.TimeUnit;

public class ThreadManager {
	ArrayList<Task> taskList = new ArrayList<Task>();
	private ExecutorService executor = Executors.newCachedThreadPool();
	private static volatile ThreadManager manager;

	private ThreadManager() {
	}

	public static ThreadManager getInstance() {
		if (manager == null) {
			synchronized (ThreadManager.class) {
				if (manager == null) {
					manager = new ThreadManager();
				}
			}
		}
		return manager;
	}

	public void execute(Task task) {
		taskList.add(task);
		executor.execute(task);
	}

	public void stopAll() {
		for (Task t : taskList)
			t.stop();
		taskList.clear();
	}

	public void reset() {
		synchronized (executor) {
			executor.shutdownNow();
			try {
				executor.awaitTermination(5, TimeUnit.SECONDS);
			} catch (Exception e) {

			}
			executor = Executors.newCachedThreadPool();
		}
	}

	public void shoutdownNow() {
		executor.shutdownNow();
	}
}
